var portaluserno = getCookie ('portaluserno')
    var configInfo=InitialParameter("/Config.json")
    // let modelApi = configInfo["modelTree"].type + '://' + configInfo["modelTree"].value  
    var modelApi = getBaseplatformPort () 
    let uploadApi = configInfo["fileUploadOrigin"].type + '://' + configInfo["fileUploadOrigin"].value  
    let shaType = true  
    let applicationName = true 
    let tableData // 应用资源管理大表 
    let selectdata,   // 选择数据库
    datatable, // 选择数据表
    analysisToolsData, // 分析工具
    applicationClassificationData // 应用分类  
    let paramsObj = {
        registerUser:portaluserno,
        systemType:'',
        analysisTools:'',
        systemStatus:1,
        name:'', 
        analysisToolValus:'',
        databaseName:'',
        tableName:'',
        type:'',
        id:'',
        shpPath:''
    }
    $(document).ready(function () { 
        if (!portaluserno) {
            location.href="/"
        } else { 
            getData ()
            whetherUploadUrl () 
        }
    })
    function whetherUploadUrl() { 
        if (shaType) { 
            paramsObj.type = 'table'
            $('#selectDatabase').attr('lay-verify','required')
            $('#selectDatabaseTable').attr('lay-verify','required')
        } else {
            paramsObj.type = 'shp'
        }
    }
    layui.use(['form','upload','element','table','layer'], function(){
        var form = layui.form
        var upload = layui.upload
        var element = layui.element
        var table = layui.table
        var layer = layui.layer   // 弹框表现
        var uploadInst = upload.render({
            elem: '#uploadFiles'  
            ,async: false,
            xhrFields: {
                withCredentials: true
            }
            ,url: uploadApi + "/sw/upload/uploadZip"  
            ,exts: 'zip'
            ,accept: 'file' 
            ,header: {
                "Access-Control-Allow-Credentials" : true,
                "Content-Type": "application/x-www-form-urlencoded"
            }
            ,data: {userNo:portaluserno}
            ,done: function(res){ 
                if (res.code == 200) {
                    paramsObj.shpPath = res.data
                    $('#selectDatabase').removeAttr('lay-verify')
                    $('#selectDatabaseTable').removeAttr('lay-verify')
                    $('#selectDatabase').attr('disabled',true)
                    $('#selectDatabaseTable').attr('disabled',true)
                    layer.msg(res.msg)
                    shaType = false
                    whetherUploadUrl () 
                }
            }
            ,error: function(){
                console.log('失败');
                //请求异常回调
            }
        }); 
        
        table.on('tool(demo)', function (obj) {
            let that = this 
            // 修改按钮点击
            if (obj.event == 'modifyThe') { 
                let addData // 存储点击当前按钮的需要在表单回显的值  
                $.ajax({
                    type: "post",
                    async: false,
                    url: modelApi + "apply/getApplyById",
                    data:{
                        id:obj.data.ID 
                    },
                    datatype: "json",
                    success: function (res) { 
                        let data = JSON.parse(res)  
                        if (data.code == 200) {
                            let datasourcePath = data.data.datasourcePath
                            addData = data.data
                        } else {
                            layui.layer.msg(data.msg, {time:1000, icon:5, shift:6})
                        }
                    }
                })
                // 把字母转换为汉字
                var spatialData = getDataDict("spatial");  
                for (key in spatialData) {
                    var oneData = spatialData[key];
                    if ( addData.systemType == '' + oneData.ZDVALUE + "" ) {
                        addData.systemType = oneData.ZDTITLE
                    }
                }
                // 结束 
                rightTable (addData.databaseName) // 获取选择数据表的函数   
                // 判断选择数据表有没有内容，有内容上传按钮禁用，没有内容可以点
                if (addData.databaseName) { // 有内容
                    $('#uploadFiles').attr('disabled',true)
                    $('#uploadFiles').addClass('layui-btn-disabled')
                    // 选择数据库填值
                    selectdata.map(item => {
                        if (item.NAME == addData.databaseName) {
                            $(`#selectDatabase option[label=${addData.databaseName}]`).attr('selected',true)
                        }
                    })
                    // 选择数据表填值
                    datatable.map(item => {
                        if (item.TABLE_NAME == addData.tableName) {
                            $(`#selectDatabaseTable option[label=${addData.tableName}]`).attr('selected',true)
                        }
                    })
                } else { // 没有内容
                    $('#uploadFiles').attr('disabled',false)
                    $('#uploadFiles').removeClass('layui-btn-disabled')
                    $('#selectDatabaseTable').empty();
                }
                // 应用名称填值
                $('.applicationName').val(obj.data.NAME)
                // 分析工具的填值
                analysisToolsData.map(item => {
                    if (item.ZDTITLE === addData.analysisTools) { 
                        $('#analysisTools option').removeAttr("selected");
                        $(`#analysisTools option[label=${item.ZDTITLE}]`).attr('selected',true)
                    } 
                })
                // 应用分类的填值 
                applicationClassificationData.map(item => {
                    if (item.ZDTITLE == addData.systemType) {
                        $(`#applicationClassification option[label=${addData.systemType}]`).attr('selected',true)
                    }
                }) 
                
                layui.form.render('select');  // 表重新渲染  
                // 赋值保存 需要的参数  
                let newSystemType
                for (key in spatialData) {
                    var oneData = spatialData[key];
                    if ( addData.systemType == '' + oneData.ZDTITLE + "" ) {
                        newSystemType = oneData.ZDVALUE
                    }
                }
                paramsObj.systemType = newSystemType
                paramsObj.analysisTools = addData.analysisTools 
                paramsObj.analysisToolValus = addData.analysisToolValus 
                paramsObj.id = addData.id 
                paramsObj.databaseName = addData.databaseName 
                paramsObj.tableName = addData.tableName 
                // 修改页面弹框
                layer.open({
                    type: 1,
                    title: "修改",
                    shadeClose: true, 
                    content: $('#modifyThe'),
                    // 关闭弹框的回调函数
                    end:function (res) {
                        $("#modifyThe").css("display",'none');
                    },
                });
            } else if (obj.event == 'authorization') {  
                // 授权按钮点击  
                initAttrTableLayer (obj.data)
                let powerData,layerId 
                layerId = obj.data.ID  
                let elemName = '#attrTable' +  layerId
                $.ajax({
                    type: "post",
                    async: false,
                    url: modelApi + "power/getApplyPowers",
                    data:{
                        applyId:obj.data.ID
                    },
                    datatype: "json",
                    success: function (res) { 
                        let data = JSON.parse(res)   
                        powerData = data.data 
                        if (data.code == 200) {
                            // 授权管理表
                            table.render({
                                elem: elemName
                                ,data:powerData
                                ,cols: [[ 
                                    {field: 'NAME',width:150, title: '部门人员', align: 'center'}
                                    ,{field: 'authorizations',width:150, title: '授权', align: 'center',toolbar:'#authorizations-table-operate'}
                                ]]
                            }) 
                        } 
                    }
                })  
                // 授权页面弹框
                layer.open({
                    type: 1,
                    title: "授权",
                    shadeClose: true, 
                    content: $('#authorizationDiv'),
                    end:function (res) {
                        $("#authorizationDiv").css("display",'none');
                    },
                    btn:['保存']
                    ,yes: function(index, layero){
                        authorizationSave (obj.data.ID,powerData) 
                        return false 
                    }, 
                    done: function(res, curr, count) {
                        powerData = layui.table.cache[layerId];
                    }
                });  
                //监听是否可查操作
                form.on('switch(authorizations)', function(obj) {
                    var index = obj.othis.parents('tr').attr("data-index");
                    if (obj.elem.checked) {
                        powerData[index].STATUS = "1";
                    } else {
                        powerData[index].STATUS = "0";
                    }
                });
            } else if (obj.event == 'deleteContent') {
                // 删除按钮点击 
                layer.confirm("确认要删除吗，删除后不能恢复", { title: "删除" }, function (index){
                    if (index) {
                        delectName (obj.data.ID)
                        layer.close(index);
                    }
                })
            } 
        }) 
        drawingTable (tableData,['NAME','ANALYSIS_TOOLS','REGISTER_DATE'])  // 页面加载调用的函数 layui-form-onswitch
        // 授权保存 
        let types = '1'
        layui.form.on('switch(encrypt)', function(data){
            if (this.checked == true) {
                types = '1'
            } else {
                types = '0' 
            }  
        })
        // 授权 
        function authorizationSave(applyId,data) { 
            let typeData = [] 
            let roleData = []
            for (let i = 0;i<data.length;i++) {
                if(data[i].STATUS == '') {
                    data[i].STATUS = '0'
                } 
                typeData.push(data[i].STATUS)
                roleData.push(data[i].NO)
            }
            let types = typeData.join(',')
            let roles = roleData.join(',') 
            $.ajax({
                type: "post",
                async: false,
                url: modelApi + "power/updateApplyPower",
                data:{
                    applyId:applyId,
                    userNo:roles,
                    type:types
                },
                datatype: "json",
                success: function (res) { 
                    let data = JSON.parse(res)  
                    if (data.code == 200) {
                        layui.layer.msg(data.msg,{ time: 1000}, function(){
                            layer.closeAll() 
                        });
                        drawingTable (tableData,['NAME','ANALYSIS_TOOLS','REGISTER_DATE']) 
                    } else {
                        layui.layer.msg(data.msg,{time:1000, icon:5, shift:6})
                    }
                }
            })
            return false
        }
        // 删除用户 
        function delectName (applyId) {
            $.ajax({
                type: "post",
                async: false,
                url: modelApi + "apply/deleteApply",
                data:{
                    applyId
                },
                datatype: "json",
                success: function (res) { 
                    let data = JSON.parse(res)  
                    if (data.code == 200) {
                        layui.layer.msg(data.msg)
                        getDataTable ()  // 重新发起获取表格的请求
                        drawingTable (tableData,['NAME','ANALYSIS_TOOLS','REGISTER_DATE']) 
                    } else {
                        layui.layer.msg(data.msg,{time:1000, icon:5, shift:6})
                    }
                }
            })
        }
        // 修改保存 
        form.on('submit(component-form-demo1)', function(data){ 
            if (applicationName) {
                paramsObj.name = $('.applicationName').val() 
                $.ajax({
                    type: "post",
                    async: false,
                    url: modelApi + "apply/updateApply",
                    data:paramsObj,
                    datatype: "json",
                    success: function (res) { 
                        let data = JSON.parse(res)  
                        if (data.code == 200) {
                            // layui.layer.msg('保存成功')
                            // layer.closeAll();    
                            getDataTable ()  
                            drawingTable (tableData,['NAME','ANALYSIS_TOOLS','REGISTER_DATE'])
                            layui.layer.msg(data.msg,{ time: 1000}, function(){
                                layer.closeAll() 
                            }); 
                        } else {
                            layui.layer.msg(data.msg, {time:1000, icon:5, shift:6})
                        }
                        layui.form.render("select");   
                    }
                });
            } else {
                layui.layer.msg('应用名称重复,请重新输入',{time:1000, icon:5, shift:6})
            }
            // layer.msg(JSON.stringify(data.field));
            return false; 
        });
        // 选择数据表内容的获取 
        form.on('select(typeData)', function(data){
            rightTable (data.value)
        });
        form.on('switch(typeDataTable)', function(data){
            if (data.value != '') {
                paramsObj.tableName = data.value
                $('#uploadFiles').attr('disabled',true)
                $('#uploadFiles').addClass('layui-btn-disabled')
            } else {
                $('#uploadFiles').attr('disabled',false)
            }
        })
        // 分析工具 
        form.on('select(analysisTools)', function(data){ 
            let arr = data.value.split(',')
            paramsObj.analysisTools = arr[0]
            paramsObj.analysisToolValus = arr[1]
        })
        // 应用分类
        form.on('select(applicationClassification)', function(data){ 
            paramsObj.systemType = data.value
        })
        form.on('submit(quxiao)',function (data) {
            layui.layer.closeAll() 
        })
    });  

    function initAttrTableLayer (data) {
        let attrTabHtml = '' 
        if (data) {
            attrTabHtml += '<table  id="attrTable' + data.ID + '" lay-filter="attrTable' + data.ID + '"></table>'
        } 
        $('#authorizationDiv').html(attrTabHtml)
    }
    let zhutiList = [] 
    // 右边选择表内容的获取 
    function rightTable (value) {
        if (value) {
            $('#uploadFiles').attr('disabled',true)
            $('#uploadFiles').addClass('layui-btn-disabled')
            layui.form.render("select");
        } else {
            $('#uploadFiles').attr('disabled',false)
            $('#uploadFiles').removeClass('layui-btn-disabled')
            $('#selectDatabaseTable').empty();
            layui.form.render("select");
        }
        paramsObj.dataBaseName = value
        let userName = portaluserno 
        let tableName = value
        $.ajax({
            type: "post",
            async: false,
            url: modelApi + "dababaseConnect/getTableByName",
            data:{
                userName,tableName
            },
            datatype: "json",
            success: function (res) { 
                let data = JSON.parse(res)  
                if (data.code == 200) { 
                    datatable = data.data
                    data.data.map(item => { 
                        $('#selectDatabaseTable').append(`<option value="${item.TABLE_NAME}" label="${item.TABLE_ALIAS}">${item.TABLE_NAME}</option>`)
                    }) 
                } else {
                    layui.layer.msg(data.msg, {time:1000, icon:5, shift:6})
                }
            }
        }); 
        layui.form.render("select");
    }
    // 表单失去焦点 验证名字是否重复
    $('.applicationName').on('blur',function () {
        let name = $('.applicationName').val() 
        if (name != '' ){
            $.ajax({
                type: "post",
                async: false,
                url: modelApi + "apply/getApplyByName",
                data:{
                    name
                },
                datatype: "json",
                success: function (res) { 
                    let data = JSON.parse(res)  
                    if (data.code == 500) {
                        applicationName = true 
                    } else {
                        applicationName = false 
                        layui.layer.msg('应用名称重复',{time:1000, icon:5, shift:6})
                    }
                }
            })
        }
    })
    function getDataTable () {
        // 表数据的获取
        $.ajax({
            type: "post",
            async: false,
            url: modelApi + "apply/getApplyByUserNo", 
            data:{
                userNo:portaluserno
            },
            datatype: "json",
            success: function (res) {  
                let data = JSON.parse(res)  
                if (data.code == 200) { 
                    tableData = data.data
                    tableData.map(item => {
                        return item.REGISTER_DATE = formatDate(item.REGISTER_DATE)
                    })
                } else {
                    layui.layer.msg(data.msg, {time:1000, icon:5, shift:6})
                }
                layui.form.render("select");
            }
        }); 
    }
    function getData () {  
        // 应用资源管理数据表格数据的请求
        getDataTable () 
        // 选择数据库第一表格数据的获取
        $.ajax({
            type: "post",
            async: false,
            url: modelApi + "dababaseConnect/getDataBaseList",
            data:{},
            datatype: "json",
            success: function (res) { 
                let data = JSON.parse(res)  
                if (data.code == 200) {
                    selectdata = data.data 
                    data.data.map(item => {  
                        $('#selectDatabase').append(`<option value="${item.NAME}" label="${item.NAME}">${item.NAME}</option>`)
                    }) 
                } else {
                    layui.layer.msg(data.msg, {time:1000, icon:5, shift:6})
                }
                layui.form.render("select");
            }
        }); 
        // 分析工具 数据的获取
        $.ajax({
            type: "post",
            async: false,
            url: modelApi + "dict/getDataDict",
            data:{
                name:'analysisType' 
            },
            datatype: "json",
            success: function (res) { 
                let data = JSON.parse(res)  
                if (data.code == 200) { 
                    analysisToolsData = data.data
                    data.data.map(item => { 
                        $('#analysisTools').append(`<option value="${item.ZDTITLE},${item.ZDVALUE}" name='analysisTools' label="${item.ZDTITLE}">${item.ZDTITLE}</option>`)
                    }) 
                } else {
                    layui.layer.msg(data.msg, {time:1000, icon:5, shift:6})
                }
                layui.form.render("select");
            }
        }); 
        // 应用分类 数据的获取 
        $.ajax({
            type: "post",
            async: false,
            url: modelApi + "dict/getDataDict",
            data:{
                name:'spatial' 
            },
            datatype: "json",
            success: function (res) { 
                let data = JSON.parse(res)  
                if (data.code == 200) { 
                    applicationClassificationData = data.data
                    data.data.map(item => { 
                        $('#applicationClassification').append(`<option value="${item.ZDVALUE}" label="${item.ZDTITLE}">${item.ZDTITLE}</option>`)
                    }) 
                } else {
                    layui.layer.msg(data.msg, {time:1000, icon:5, shift:6})
                }
                layui.form.render("select");
            }
        });
    }    
    // 查询按钮 
    
    $('#query').on('click',function () {
        // resourcesName   || status  ||    selectTime 
        $.ajax({
            type: "post",
            async: false,
            url: modelApi + "apply/getApplyByKey",
            data:{
                /*
                getApplyByKey(String name, String status, String registerTime,String userNo)
                name：表格名字   status:启动 注销   status:admin
                */ 
                name:$('#resourcesName').val(),
                status:$('#status').val(),
                registerTime:$('#selectTime').val(),
                userNo:portaluserno
            },
            datatype: "json",
            success: function (res) { 
                let data = JSON.parse(res)  
                if (data.code == 200) { 
                    data.data.map(item => {
                        return item.REGISTER_DATE = formatDate(item.REGISTER_DATE)
                    })
                    drawingTable (data.data,['NAME','ANALYSIS_TOOLS','SYSTEM_STATUS','REGISTER_DATE']) 
                } else {
                    layui.layer.msg(data.msg, {time:1000, icon:5, shift:6})
                }
                layui.form.render("select");
            }
        }); 
        return false 
    })
    $('#btn_reset').on('click',function () {
        $("#ipt_search").val(''); 
        drawingTable (tableData,['NAME','ANALYSIS_TOOLS','REGISTER_DATE'])  // 页面加载调用的函数 layui-form-onswitch
    }) 
    $(".registeredApplication").on('click',function () {
        layer.open({
            type: 2,
            title: '注册应用服务',
            shadeClose: true,
            shade: 0.8,
            area: ['800px', '480px'],
            content: '/BasePlatform/applicationSystem/dispose.html' //iframe的url
        });
    })
    function drawingTable (data,arr) {
        layui.table.render({
            elem: '#demo'
            ,data:data
            ,page:true
            ,limit:5
            ,limits:[5,10,15]
            ,cols: [[ //表头
                {field: arr[0],width:250, title: '应用资源名称', align: 'center'}
                ,{field: arr[1], title: '分类', align: 'center'}
                ,{field: arr[2], title: '注册时间', align: 'center'}
                ,{field: 'operation', title: '操作',align: 'center', toolbar: '#delivery-table-operate' }
            ]]
        })
    }
    $('#preserveDeploy').on('click',function () {
        layer.closeAll() 
    }) 
    